<template>
  <div class="search_container">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-bottom: 8px">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>借阅证管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card shadow="always">
      <!-- 搜索内容和导出区域 -->
      <el-row :gutter="10" style="margin-bottom: 8px">
        <el-row :span="1.3" style="line-height: 40px">
          <span>条件搜索:</span>
        </el-row>
        <el-col :span="3">
          <el-select
            v-model="queryInfo.query"
            filterable
            placeholder="请选择"
            style="margin-left: 15px"
            size="large"
          >
            <el-option
              v-for="item in searchs"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="1"></el-col>
        <el-col :span="3">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.condition"
            class="input-with-select"
            @keyup.enter.native="getStatementList"
            size="large"
          ></el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" class="el-icon-printer" size="large" @click="getStatementList">
            <el-icon><Search /></el-icon>
          </el-button>
        </el-col>
        <el-col :span="1"></el-col>
        <el-col :span="4">
          <el-button type="primary" @click="showAddDialog()" size="large">
            <i class="el-icon-plus"></i>
            添加借阅证
          </el-button>
        </el-col>
        <el-col :span="1"></el-col>
        <el-col :span="2" style="float: right">
          <!-- <el-button type="primary" class="el-icon-printer" size="large" @click="exportToExcel">
            导出Excel
          </el-button> -->
        </el-col>
        <el-col :span="1"></el-col>

        <el-col :span="2"></el-col>
        <el-col :span="2" style="float: right">
          <el-button type="success" class="el-icon-full-screen" size="large" @click="fullScreen">
            全屏
          </el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table
        :data="tableData"
        show-overflow-tooltip
        style="width: 100%"
        id="pdfDom"
        :default-sort="{ prop: 'cardNumber', order: 'ascending' }"
        v-loading="loading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
      >
        <el-table-column type="index"></el-table-column>

        <el-table-column prop="Username" label="用户名"></el-table-column>
        <el-table-column prop="RuleNumber" label="借阅规则"></el-table-column>
        <el-table-column prop="Status" label="借阅证状态"></el-table-column>
        <el-table-column prop="CardNumber" label="卡片编号" sortable></el-table-column>
        <el-table-column prop="UpdateTime" label="创建时间" sortable></el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <!-- 修改按钮 -->
            <el-button type="primary" @click="showEditDialog(row.UserID)">
              <el-icon><EditPen /></el-icon>
            </el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" @click="removeUserById(row.UserID)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页查询区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[1, 2, 3, 4, 5]"
        :page-size="queryInfo.size"
        layout="total,prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <!-- 修改规则的对话框 -->
      <el-dialog
        title="修改借阅证"
        v-model="editDialogVisible"
        width="50%"
        @close="editDialogClosed"
      >
        <el-form :model="editForm" ref="editFormRef" :rules="editFormRules" label-width="120px">
          <el-form-item label="卡片编号" prop="userId">
            <el-input v-model="editForm.userId"></el-input>
          </el-form-item>
          <el-form-item label="名称" prop="userName">
            <el-input v-model="editForm.userName"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="editForm.password" type="password"></el-input>
          </el-form-item>
          <el-form-item label="规则" prop="ruleNumber">
            <el-select v-model="editForm.ruleNumber" placeholder="请选择">
              <el-option
                v-for="item in formattedLists"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="userStatus">
            <el-radio-group v-model="edituserStatus">
              <el-radio value="1">可用</el-radio>
              <el-radio value="0">挂失</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateStatement">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 添加书籍的对话框 -->
      <el-dialog title="添加借书证" v-model="addDialogVisible" width="50%" @close="addDialogClosed">
        <el-form :model="addForm" ref="addFormRef" :rules="addFormRules" label-width="120px">
          <el-form-item label="账号" prop="username">
            <el-input v-model="addForm.userName"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="规则" prop="ruleNumber">
            <el-select v-model="addForm.ruleNumber" placeholder="请选择">
              <el-option
                v-for="item in formattedLists"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="userStatus">
            <el-radio-group v-model="adduserStatus">
              <el-radio value="1">可用</el-radio>
              <el-radio value="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addStatement">添加借阅证</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import * as XLSX from "xlsx";
import {
  getBorrowList,
  getBorrowRules,
  addBorrow,
  getOneBorrow,
  postOneBorrow,
  delOneBorrow,
} from "../../api/api";

let tableData = ref();
//编辑框是否显示
const editDialogVisible = ref(false);
//用来转换状态的中间值
let edituserStatus = ref();
//编辑表单
const editForm = reactive({
  userName: null,
  password: "",
  ruleNumber: null,
  userId: "",
  userStatus: "",
});
//编辑规则
const editFormRules = reactive({});
//添加框是否显示
const addDialogVisible = ref(false);
//用来转换状态的中间值
let adduserStatus = ref();
//添加表单
const addForm = reactive({
  userName: "",
  password: "",
  ruleNumber: null,
  userStatus: 0,
});
//添加规则
const addFormRules = reactive({});
//借阅规则
const searchs = [
  {
    value: "card_number",
    label: "借阅证编号",
  },
  {
    value: "username",
    label: "用户名",
  },
  {
    value: "rule_number",
    label: "借阅规则",
  },
];
let bookRuleIdLists = ref([]);
const queryInfo = reactive({
  pageNum: 1,
  size: 5,
  condition: "",
  query: "",
});
const total = ref(0);
const title = "借阅证管理";
const json_fields = {
  借阅证遍号: "cardNumber",
  用户名: "username",
  借阅规则: "ruleNumber",
  状态: "status",
};
let formattedLists = ref();
const loading = ref(true);

onMounted(() => {
  getStatementList();
});

const handleSizeChange = val => {
  queryInfo.size = val;
  getStatementList();
};
const handleCurrentChange = val => {
  queryInfo.pageNum = val;
  getStatementList();
};
//让修改公告的对话框可见,并从数据库中回显数据
const showEditDialog = id => {
  editDialogVisible.value = true;
  //获取指定借阅证;
  getOneBorrow(id)
    .then(res => {
      editForm.userName = res.data.Username;
      editForm.password = null;
      editForm.ruleNumber = res.data.RuleNumber;
      editForm.userId = res.data.CardNumber;
      editForm.userStatus = res.data.UserStatus;
      ElMessage({
        message: "获取信息成功",
        type: "success",
      });
    })
    .catch(err => {
      console.log(err, "err");
      ElMessage.error("获取信息失败");
    });
  //获取规则列表
  getBorrowRules()
    .then(res => {
      bookRuleIdLists.value = res.data;
      formattedLists.value = bookRuleIdLists.value.map(id => {
        return {
          label: id.toString(), // 或者任何你想作为显示文本的转换
          value: id,
        };
      });
      console.log(formattedLists.value);
      ElMessage({
        message: "获取规则成功",
        type: "success",
      });
    })
    .catch(err => {
      console.log(err, "err");
      ElMessage.error("获取规则失败");
    });
};

//修改借阅证
const updateStatement = () => {
  editForm.userStatus = Number(edituserStatus.value);
  postOneBorrow(editForm)
    .then(res => {
      console.log(res.data, "111");
      ElMessage({
        message: "修改借阅证成功",
        type: "success",
      });
    })
    .then(res => getStatementList())
    .catch(err => {
      if (err.response.data.message == "LibraryCard Username Already Exists") {
        ElMessage.error("用户名已存在，请重现尝试");
      }
      console.log(err, "err");
      ElMessage.error("修改借阅证失败");
    });

  editDialogVisible.value = false;
};
//监听修改对话框的关闭，一旦对话框关闭，就重置表单，回显数据
const editDialogClosed = () => {
  // $refs.editFormRef.resetFields();
  // editForm.checkList = ["南图", "北图", "教师之家"];
};
//删除公告
const removeUserById = id => {
  delOneBorrow(id)
    .then(res => {
      console.log(res.data, "111");
      ElMessage({
        message: "删除借阅证成功",
        type: "success",
      });
    })
    .then(res => {
      getStatementList();
    })
    .catch(err => {
      console.log(err, "err");
      ElMessage.error("删除借阅证失败");
    });
};
//监听加公告对话框的关闭，一旦对话框关闭，就重置表单
const addDialogClosed = () => {
  // $refs.addFormRef.resetFields();
};
//当用户点击发送新公告时，让添加对话框的visible改为true
const showAddDialog = () => {
  getBorrowRules()
    .then(res => {
      bookRuleIdLists.value = res.data;
      formattedLists.value = bookRuleIdLists.value.map(id => {
        return {
          label: id.toString(), // 或者任何你想作为显示文本的转换
          value: id,
        };
      });
      console.log(formattedLists.value);
      ElMessage({
        message: "获取规则成功",
        type: "success",
      });
    })
    .catch(err => {
      console.log(err, "err");
      ElMessage.error("获取规则失败");
    });
  addDialogVisible.value = true;
};
//获取借阅证列表
const getStatementList = () => {
  loading.value = true;
  getBorrowList(queryInfo)
    .then(res => {
      tableData.value = res.data.records;
      total.value = parseInt(res.data.total);
      console.log(tableData.value, "111");
      ElMessage({
        message: "获取信息成功",
        type: "success",
      });
    })
    .catch(err => {
      console.log(err, "err");
      ElMessage.error("获取信息失败");
    });

  loading.value = false;
};

//增加借阅证
const addStatement = () => {
  addForm.userStatus = Number(adduserStatus.value);
  addBorrow(addForm)
    .then(res => {
      console.log(res.data, "111");
      ElMessage({
        message: "增加借阅证成功",
        type: "success",
      });
    })
    .then(res => {
      getStatementList();
    })
    .catch(err => {
      if (err.response.data.message == "LibraryCard Username Already Exists") {
        ElMessage.error("用户名已存在，请重现尝试");
      }
      console.log(err.response.data.message);
      ElMessage.error("增加借阅证失败");
    });
  addDialogVisible.value = false;
};

const downLoad = () => {
  getPdf(title);
};
const fullScreen = () => {
  // Dom对象的一个属性: 可以用来判断当前是否为全屏模式(trueORfalse)
  let full = document.fullscreenElement;
  // 切换为全屏模式
  if (!full) {
    // 文档根节点的方法requestFullscreen实现全屏模式
    document.documentElement.requestFullscreen();
  } else {
    // 退出全屏模式
    document.exitFullscreen();
  }
};
</script>

<style></style>
